﻿using ConfExpert.Datasets;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Kauf
{
    public partial class MagazaDagilimi : XPopupForm
    {

        int idx = -1;
        int dagilimId = -1;
        //public DataTable dtTotalMagaza = new DataTable();
        DataTable dtDagilim = null;

        public MagazaDagilimi(int idx, int dagilimId)
        {
            InitializeComponent();
            txtInfo.Caption = "Idx. " + idx.ToString();
            this.idx = idx;
            this.dagilimId = dagilimId;
        }

        private void MagazaDagilimi_Load(object sender, EventArgs e)
        {
            dtDagilim = ExecuteDataTable("GetMagazaDagilim", idx);
            dtDagilim.Columns.Add("Ayir", typeof(bool));
            dtDagilim.Columns.Add("Sira", typeof(int));
            dtDagilim.Columns.Add("Parçalandı", typeof(bool));
            dtDagilim.Columns.Add("BaseIdx", typeof(int));

            for (int i = 0; i < dtDagilim.Rows.Count; i++)
            {
                dtDagilim.Rows[i]["Ayir"] = false;
                dtDagilim.Rows[i]["Parçalandı"] = false;
                dtDagilim.Rows[i]["Sira"] = i * 10;
            }

            dtDagilim.SetPK("idx");
            dtDagilim.AddAutoIncrementalColumn("idx");

            dtDagilim.ColumnChanging += dtDagilim_ColumnChanging;

            gv.Init(dtDagilim);
            gv.Columns["Ayir"].VisibleIndex = 0;


            MyData.DagilimRow r = AppSession.Lookups.Dagilim.FindByDagilimId(dagilimId);
            if (r != null)
                for (int i = 1; i < 29; i++)
                {
                    string fieldName = String.Format("A{0:00}", i);
                    string cap = r[String.Format("A{0:00}", i)].ToString();

                    if (cap != "")
                    {
                        gv.Columns[fieldName].Caption = cap;
                        gv.AddSummary(fieldName);
                    }
                    else
                        gv.Columns[fieldName].Visible = false;
                }

            GridManager gm = gv.GetManager();
            gm.Utility.SadeceDoluSutunlariGoster(true);
            gm.GridMenu.AddMenu("Parçala", Parcala);
            gv.MakeColumnInvisible("idx", "KaufOrdersIdx", "Sira", "Parçalandı");

            gv.BeginSort();
            gv.Columns["Sira"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            gv.EndSort();

            gv.RowCellClick += gv_RowCellClick;
            gv.RowCellStyle += gv_RowCellStyle;
            dtDagilim.AcceptChanges();
            //gv.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gv.BestFitColumns();
        }

        void gv_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                DataRow dr = gv.GetDataRow(e.RowHandle);
                if ((bool)dr["Parçalandı"])
                {
                    int index = gv.GetRowCellValue(e.RowHandle, "Sira").ToInt() / 10;
                    Color[] colors = new Color[] { Color.Khaki, Color.Gold, Color.Yellow };

                    e.Appearance.BackColor = colors[index % 3];
                }
            }
        }

        void dtDagilim_ColumnChanging(object sender, DataColumnChangeEventArgs e)
        {
            if (!(bool)e.Row["Parçalandı"])
                return;

            dtDagilim.ColumnChanging -= dtDagilim_ColumnChanging;
            int sira = e.Row["Sira"].ToInt();
            int tamSira = (sira / 10 * 10);

            DataRow drParent = dtDagilim.Select("Sira = " + tamSira.ToStr())[0];
            DataRow drChild = dtDagilim.Select("Sira = " + (tamSira + 1))[0];

            int qtyChild = drChild[e.Column].ToInt();
            int qtyParent = drParent[e.Column].ToInt();
            int qtyNew = e.ProposedValue.ToInt();
            int total = qtyChild + qtyParent;

            if (sira % 10 == 0) //Parent
            {
                if (total - qtyNew >= 0)
                    drChild[e.Column] = total - qtyNew;
                else
                    e.ProposedValue = qtyParent; //cancel
            }
            else //Child
            {
                if (total - qtyNew >= 0)
                    drParent[e.Column] = total - qtyNew;
                else
                    e.ProposedValue = qtyChild; //cancel
            }

            gc.RefreshDataSource();

            dtDagilim.ColumnChanging += dtDagilim_ColumnChanging;
        }

        private void Parcala(object sender, EventArgs e)
        {
            if (gv.FocusedRowHandle > -1)
            {
                DataRow drCurrent = gv.GetFocusedDataRow();
                if ((bool)drCurrent["Parçalandı"] == false)
                {
                    dtDagilim.ColumnChanging -= dtDagilim_ColumnChanging;

                    DataRow drNew = dtDagilim.NewRow();

                    foreach (System.Data.DataColumn col in dtDagilim.Columns)
                    {
                        if (!"idx TS".Contains(col.ColumnName))
                            drNew[col] = drCurrent[col];
                    }

                    for (int i = 1; i < 29; i++)
                    {
                        string fieldName = String.Format("A{0:00}", i);
                        drCurrent[fieldName] = DBNull.Value;
                    }

                    drNew["Ayir"] = true;
                    drNew["Sira"] = drCurrent["Sira"].ToInt() + 1;
                    drNew["Parçalandı"] = true;
                    drNew["BaseIdx"] = drCurrent["idx"];

                    dtDagilim.Rows.Add(drNew);
                    drCurrent["Parçalandı"] = true;

                    gv.BeginSort();
                    gv.Columns["Sira"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    gv.EndSort();

                    dtDagilim.ColumnChanging += dtDagilim_ColumnChanging;
                }
            }
        }

        void gv_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Ayir")
                {
                    bool currentStatus = (bool)e.CellValue;
                    gv.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
                }
            }
        }

        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.EndEditing();
            DialogResult ds = XtraMessageBox.Show("Daha önceden girilmiş adetler silinip yerine yeni değerler yazılacak. Emin misiniz?", "Uyarı", MessageBoxButtons.YesNo);
            if (ds == System.Windows.Forms.DialogResult.Yes)
            {
                gv.EndEditing();

                DataTable dt = dtDagilim.GetChanges();
                string xml = dt.Serialize();

                Orders = ExecuteDataTable("InsNewOrderByMagazaDagilim2", xml);

                //DataRow[] dtx = dtDagilim.Select("    ;
                //dtTotalMagaza.Rows.Add(dtTotalMagaza.NewRow());

                //for (int i = 1; i < 29; i++)
                //{
                //    string fieldName = String.Format("A{0:00}", i);
                //    dtTotalMagaza.Columns.Add(fieldName, typeof(int));
                //    int adet = 0;
                //    foreach (DataRow dr in dtx)
                //        adet += dr[fieldName].ToInt();

                //    if (adet > 0)
                //        dtTotalMagaza.Rows[0][fieldName] = adet;
                //}
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        public DataTable Orders { get; set; }
    }
}